import logging, os, re, shutil
from PyQt5 import QtCore
from PyQt5.QtWidgets import QWidget, QLabel, QVBoxLayout, QPushButton, QFileDialog, QMessageBox
from utils.faceUtil import face_detect_and_save


class FaceView(QWidget):
    data = QtCore.pyqtSignal(list)

    def __init__(self):
        super().__init__()
        self.label = QLabel("人脸录入")
        self.init()

    def init(self):
        layout = QVBoxLayout()

        button_add = QPushButton("添加图片")
        button_add.clicked.connect(self.open_file)

        layout.addWidget(button_add)

        self.setLayout(layout)
        self.show()

    def open_file(self):
        """
        打开多张图片，将第一张图片显示出来
        :return:
        """
        name = ''
        identify_result = '人脸识别失败'
        # 文件选择框
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        file_paths, _ = QFileDialog.getOpenFileNames(self, "选择图片", "/Desktop", "图片文件 (*.png *.jpg *.jpeg *.gif *.bmp)")
        if file_paths:
            # pixmap = QPixmap(file_paths[0])
            # # 调整大小，例如将图片调整为宽度100px，高度自动调整以保持比例
            # pixmap = pixmap.scaled(self.width(), self.height(), Qt.KeepAspectRatio, Qt.SmoothTransformation)
            for index, value in enumerate(file_paths):
                #  检查图片命名是否合规 【姓名_身份证】的格式
                result = value.split('/')
                pattern = re.compile(r'.*_.*')
                if not pattern.match(result[len(result) - 1]):
                    identify_result = result[len(result) - 1] + '图片名称格式非法'
                else:
                    # 识别图片特征点，保存到data_face.json
                    name = face_detect_and_save(value)
            if len(name) > 0:
                identify_result = name + '人脸录入成功！'
            msg = QMessageBox()
            msg.information(self, '提醒', identify_result, QMessageBox.Ok)
